export class Queue {
  items = []

  //向队列尾部添加一个（或多个）新的项
  enqueue (element) {
    this.items.push(element)
  }
  //移除队列的第一（即排在队列最前面的）项，并返回被移除的元素
  dequeue () {
    return this.items.shift()
  }
  //返回队列中第一个元素--最先被添加，也将是最先被移除的元素。队列不做任何变动（不移除元素，只返回元素信息--与stack类的peek类似）
  front () {
    if (this.isEmpty()) return null
    return this.items[0]
  }
  //如果队列中不包含任何元素，返回true，否则返回false
  isEmpty () {
    return this.items.length === 0
  }
  //返回队列包含的元素个数，与数组length属性类似
  size () {
    return this.items.length
  }
}

class QueueElement {
  constructor (element, priority) {
    this.element = element
    this.priority = priority
  }
}

export class PriorityQueue extends Queue {
  enqueue (element, priority) {
    const queueElement = new QueueElement(element, priority)

    if (this.isEmpty()) {
      this.items.push(queueElement)
    } else {
      let added = false
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].priority > queueElement.priority) {
          this.items.splice(i, 0, queueElement)
          added = true
          break
        }
      }

      if (!added) {
        this.items.push(queueElement)
      }
    }
  }
}

export function passGame(nameList, num) {
  const queue = new Queue()
  for (const name of nameList) {
    queue.enqueue(name)
  }

  while (queue.size() > 1) {
    for (let i = 0; i < num-1; i++) {
      queue.enqueue(queue.dequeue())
    }

    queue.dequeue()
  }

  return queue.front()
}